package com.Jeu;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.view.Window;
import android.content.SharedPreferences;

import java.io.IOException;
import java.util.*;

public class NewGame extends Activity {
	public static boolean run = true;
	private int score = 0;
	private int numClickTotal = 0;
	private int bonusScore = 0;
	private int factor;
	private Context mContext;
	private int numClick = 0;
	private int numImgRes = 0;
	private SharedPreferences pref;

	// private boolean[] click = { false, false, false, false, false, false,
	// false, false, false, false, false, false, false, false, false,
	// false };

	private Integer[] mThumbIds = { R.drawable.carton, R.drawable.carton,
			R.drawable.carton, R.drawable.carton, R.drawable.carton,
			R.drawable.carton, R.drawable.carton, R.drawable.carton,
			R.drawable.carton, R.drawable.carton, R.drawable.carton,
			R.drawable.carton, R.drawable.carton, R.drawable.carton,
			R.drawable.carton, R.drawable.carton };

	// Creation des position par hasard
	private Integer[] imgs = RandomImages();

	private long id_Ancien = 0;
	private long position_Ancien = 0;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
				
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newgame);
		GridView gridview = (GridView) findViewById(R.id.gridview);
		updateScore();

		final ImageAdapter adapter = new ImageAdapter(this);
		gridview.setAdapter(adapter);

		

		gridview.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {

				// Si on voit 2 images, on cache tous les cartons
				if (numClick == 2) {
					for (int i = 0; i < mThumbIds.length; i++) {
						if (mThumbIds[i] != -1) {
							ImageView imageView = (ImageView) parent
									.getChildAt(i);
							imageView.setImageResource(mThumbIds[i]);
						}
					}
					numClick = 0;
				}

				// long ID_Temp = parent.getItemIdAtPosition(position);
				long ID_Temp = imgs[position];

				ImageView imageView = (ImageView) v;
				if (mThumbIds[position] != -1) {
					imageView.setImageResource(imgs[position]);
					numClick++;
					numClickTotal++;
					if (numClick == 1) {
						id_Ancien = ID_Temp;
						position_Ancien = position;
					}
				}

				if (numClick == 2 && id_Ancien == ID_Temp
						&& position != position_Ancien) {
					// cacher deux images identiques
					for (int i = 0; i < imgs.length; i++) {
						if (imgs[i] == id_Ancien && mThumbIds[i] != -1) {
							ImageView image = (ImageView) parent.getChildAt(i);
							image.setImageResource(-1);

							// noter le carton et l'image ont deja cache
							mThumbIds[i] = -1;
							imgs[i] = -1;

							// le nombre l'image est deja ouvert
							numImgRes++;

							// Toast.makeText(NewGame.this," res:" + numImgRes,
							// Toast.LENGTH_SHORT).show();
							score += 10;
							updateScore();
						}
					}
					numClick = 0;
				}

				// Si on a ouvet toutes les images
				if (numImgRes == 16) {
					run = false;
					bonusScore = Timer.currentTime;
					pref = getSharedPreferences("checkPrf", MODE_PRIVATE);
					factor = pref.getInt("check", factor);
					// factor = ModeGame.check;
					bonusScore *= factor;
					score += bonusScore;
					score -= numClickTotal * 2;
					updateScore();
					AlertDialog messAlert = new AlertDialog.Builder(
							NewGame.this).create();
					messAlert.setTitle("GAME OVER");
					messAlert.setMessage("Do you want to replay this game?");
					messAlert.setButton("Yes",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
									Intent NewgameIntent = new Intent(
											NewGame.this, NewGame.class);
									startActivity(NewgameIntent);
									run = true;
								}
							});
					messAlert.setButton2("No",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
									Intent MenuIntent = new Intent(
											NewGame.this, Menu.class);
									startActivity(MenuIntent);
									run = true;
								}
							});
					messAlert.show();

					// Calculer le score

					// Sauvegarder le score
					saveHighScore(100, "abc");
				}


			}
		});

	}

	private void updateScore() {
		// score = Timer.currentTime;
		TextView ViewScore = (TextView) findViewById(R.id.ViewScore);
		ViewScore.setText(String.valueOf(score));
	}

	private void saveHighScore(long score, String name) {
	
		 pref = this.getSharedPreferences(Options.PREF_FILE,Activity.MODE_PRIVATE);
		 SharedPreferences.Editor editor = pref.edit();
		 
		 // get list score 		
		 long number = 0;
		 boolean flag = true;
		 for(int i = 0 ; i < 5 && flag; i++)
		 {
			 String x_score = "score" + (i+1);
			 String x_name = "name_score"+ (i + 1); 
			 
			 long num = 0;
			 try
			 {
				 num = pref.getLong(x_score, number);
			 }catch(Exception e)
			 {
				 num = 0;
			 }
			 
			 if(score > num)
			 {
				 editor.putLong(x_score, score);
				 editor.putString(x_name, name);
				 flag = false;
			 }
			 
		 }		 
		 editor.commit(); 
		
	}

	// Creation des position par hasard
	private Integer[] RandomImages() {
		Integer[] image = { R.drawable.spa1, R.drawable.spa3, R.drawable.spa5,
				R.drawable.spa7, R.drawable.spa2, R.drawable.spa4,
				R.drawable.spa6, R.drawable.spa8, R.drawable.spa1,
				R.drawable.spa2, R.drawable.spa3, R.drawable.spa4,
				R.drawable.spa5, R.drawable.spa6, R.drawable.spa7,
				R.drawable.spa8 };

		// create a Vector object
		Vector list = new Vector();

		for (int i = 0; i < image.length; i++) {
			list.add(image[i]);
		}

		Random random = new Random(System.currentTimeMillis());
		Collections.shuffle(list, random);

		list.copyInto(image);

		return image;
	}

}